<?php

namespace app\cps\service;

use app\model\Money;
use app\model\RechargeTemplate;
use app\model\ResponsibilityPerson;
use app\common\Error;
use app\model\Link;
use app\model\StatisticsVideoRechargeData;
use app\model\Videos;
use think\facade\Db;
use app\model\RechargeLimitTemplateCompany;
use app\model\RechargeLimitTemplateVideo;
use app\model\RechargeLimitTemplate;

class RechargeService
{
    private $moneyModel;
    private $model;
    private $responsibilityPersonModel;
    private $linkModel;
    private $statisticsVideoRechargeDataModel;
    private $videosModel;
    private $rechargeLimitTemplateCompanyModel;
    private $rechargeLimitTemplateVideoModel;
    private $rechargeLimitTemplateModel;

    public function __construct(RechargeTemplate $model, Money $moneyModel, ResponsibilityPerson $responsibilityPersonModel, Link $linkModel, StatisticsVideoRechargeData $statisticsVideoRechargeDataModel, Videos $videosModel, RechargeLimitTemplateCompany $rechargeLimitTemplateCompanyModel, RechargeLimitTemplateVideo $rechargeLimitTemplateVideoModel, RechargeLimitTemplate $rechargeLimitTemplateModel)
    {
        $this->model = $model;
        $this->moneyModel = $moneyModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->linkModel = $linkModel;
        $this->statisticsVideoRechargeDataModel = $statisticsVideoRechargeDataModel;
        $this->videosModel = $videosModel;
        $this->rechargeLimitTemplateCompanyModel = $rechargeLimitTemplateCompanyModel;
        $this->rechargeLimitTemplateVideoModel = $rechargeLimitTemplateVideoModel;
        $this->rechargeLimitTemplateModel = $rechargeLimitTemplateModel;
    }

    // 获取总后台充值设置列表
    public function getRechargeSetList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['is_delete', '=', 0];
        $where[] = ['is_display', '=', 1];

        if (!empty($params['platform_type'])) {
            $where[] = ['platform_type', '=', $params['platform_type']];
        }

        if (!empty($params['display_object'])) {
            $where[] = ['display_object', '=', $params['display_object']];
        }

        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%'.$params['name'].'%'];
        }

        $data = $this->moneyModel->getPagingDataByWhere($where, $page, $limit, 'id, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title, platform_type, type', 'recharge_price desc');

        return $data;
    }

    // 获取自定义充值设置列表
    public function getCustomRechargeSetList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['responsibility_person_id', '=', $responsibilityPersonId];
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
        } else {
            $where[] = ['official_account_id', '=', $userInfo['cps_used_official_account_id']];
        }
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, responsibility_person_id, name, created_at, updated_at, recharged_content, not_recharged_content, type');

        if (!empty($data['data'])) {
            $responsibilityPersonIds = array_column($data['data'], 'responsibility_person_id');

            $responsibilityPersonIds = array_unique($responsibilityPersonIds);

            $responsibilityPerson = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');

            $responsibilityPersonData = array_column($responsibilityPerson, 'name', 'id');

            $ids = array_column($data['data'], 'id');
            $linkData = $this->linkModel->getDataByWhere(['recharge_template_id' => $ids], 'id, recharge_template_id');
            $link = [];
            foreach ($linkData as $key => $value) {
                $link[$value['recharge_template_id']][] = $value['id'];
            }

            foreach ($data['data'] as $key => $item) {

                $data['data'][$key]['responsibility_person_name'] = empty($responsibilityPersonData[$item['responsibility_person_id']]) ? '' : $responsibilityPersonData[$item['responsibility_person_id']];
                $data['data'][$key]['recharged_content'] = json_decode($item['recharged_content'], true);
                $data['data'][$key]['not_recharged_content'] = json_decode($item['not_recharged_content'], true);
                $data['data'][$key]['link_ids'] = empty($link[$item['id']]) ? '' : implode(',', $link[$item['id']]);
            }
        }
        return $data;
    }

    // 获取自定义充值设置详情
    public function getCustomRechargeSetDetail($id)
    {
        $data = $this->model->getInfoByWhere(['id' => $id], 'id, name, recharged_content, not_recharged_content, type');

        $data['recharged_content'] = json_decode($data['recharged_content'], true);
        $data['not_recharged_content'] = json_decode($data['not_recharged_content'], true);

        return $data;
    }

    // 添加/修改自定义充值设置
    public function editCustomRechargeSet($params, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];

        if (empty($params['recharged_content']) && empty($params['not_recharged_content'])) {
            return ['message' => Error::NO_CONTENT_AT_THE_SAME_TIME];
        }

        if (empty($params['id'])) {
            $params['created_at'] = time();
            $params['official_account_id'] = $officialAccountId;
            $params['responsibility_person_id'] = $userInfo['cps_user_id'];
        } else {
            $params['updated_at'] = time();

            // 判断是否开启了充值限制、使用的链接对应短剧是不是新剧
            $useLinkData = $this->linkModel->getDataByWhere(['recharge_template_id' => $params['id']], 'id, video_id, responsibility_person_id');

            $videoIds = array_column($useLinkData, 'video_id');
            $responsibilityPersonIds = array_column($useLinkData, 'responsibility_person_id');
            $companyIds = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'company_id');
            $companyIds = array_column($companyIds, 'company_id');

            $rechargeLimitTemplateVideoData = $this->rechargeLimitTemplateVideoModel->getDataByWhere(['video_id' => $videoIds], 'recharge_limit_template_id, video_id');

            $rechargeLimitTemplateIds = array_column($rechargeLimitTemplateVideoData, 'recharge_limit_template_id');
            $rechargeLimitTemplateCompanyData = $this->rechargeLimitTemplateCompanyModel->getDataByWhere(['recharge_limit_template_id' => $rechargeLimitTemplateIds], 'company_id');

            $bool = false;
            if ($rechargeLimitTemplateCompanyData) {
                foreach ($rechargeLimitTemplateCompanyData as $key => $value) {
                    if (!in_array($value['company_id'], $companyIds)) {
                        $bool = true;
                        break;
                    }
                }
            }

            // $bool = false;
            // foreach ($videoData as $item) {
            //     $time = $item['launch_start_time'] ? $item['launch_start_time'] : $item['created_at'];
            //     if ($time > time() - config('link.limit_start_time')) {
            //         $bool = true;
            //         break;
            //     }
            // }

            if ($bool) {
                $videoData = $this->videosModel->getDataByIds($videoIds, 'id, launch_start_time, created_at');

                // $rechargeLimitData = Db::name('recharge_limit_switch_setting')
                //     ->field('start_charge_drama_series_limit, bottom_price_limit')
                //     ->where(['id' => config('link.id')])
                //     ->find();
                $video = array_column($videoData, 'launch_start_time', 'id');
                $rechargeLimitTemplateVideo = array_column($rechargeLimitTemplateVideoData, 'recharge_limit_template_id', 'video_id');

                foreach ($useLinkData as $key => $value) {
                    $limitBool = false;
                    if (!empty($rechargeLimitTemplateVideo[$value['video_id']])) {
                        $rechargeLimitTemplateData = $this->rechargeLimitTemplateModel->getInfoByWhere(['id' => $rechargeLimitTemplateVideo[$value['video_id']]]);

                        if ($rechargeLimitTemplateData) {
                            $time = $video[$value['video_id']];
                            if ($time > time() - $rechargeLimitTemplateData['recharge_day'] * 86400) {
                                $limitBool = true;
                            }
                        }

                        if ($limitBool) {
                            $rechargedContent = json_decode($params['recharged_content'], true);
                            $notRechargedContent = json_decode($params['not_recharged_content'], true);

                            if (!empty($rechargedContent) && is_array($rechargedContent)) {
                                foreach ($rechargedContent as $item) {
                                    if ($item['recharge_price'] < $rechargeLimitTemplateData['recharge_amount']) {
                                        return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT.'（'.$rechargeLimitTemplateData['recharge_amount'].'）'];
                                    }
                                }
                            }
                            if (!empty($notRechargedContent) && is_array($notRechargedContent)) {
                                foreach ($notRechargedContent as $item) {
                                    if ($item['recharge_price'] < $rechargeLimitTemplateData['recharge_amount']) {
                                        return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT.'（'.$rechargeLimitTemplateData['recharge_amount'].'）'];
                                    }
                                }
                            }
                        }
                    }
                }

                // if ($rechargeLimitData['bottom_price_limit'] == 1) {
                //     $rechargedContent = json_decode($params['recharged_content'], true);
                //     $notRechargedContent = json_decode($params['not_recharged_content'], true);

                //     if (!empty($rechargedContent) && is_array($rechargedContent)) {
                //         foreach ($rechargedContent as $item) {
                //             if ($item['recharge_price'] < config('link.limit_amount')) {
                //                 return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT.'（'.config('link.limit_amount').'）'];
                //             }
                //         }
                //     }
                //     if (!empty($notRechargedContent) && is_array($notRechargedContent)) {
                //         foreach ($notRechargedContent as $item) {
                //             if ($item['recharge_price'] < config('link.limit_amount')) {
                //                 return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT.'（'.config('link.limit_amount').'）'];
                //             }
                //         }
                //     }
                // }
            }
        }

        if (!empty($params['recharged_content'])) {
            $params['recharged_content'] = json_encode($params['recharged_content']);
        }

        if (!empty($params['not_recharged_content'])) {
            $params['not_recharged_content'] = json_encode($params['not_recharged_content']);
        }

        $id = $this->model->edit($params);

        return $id ? true : false;
    }

    // 删除自定义充值设置
    public function deleteCustomRechargeSet(int $id)
    {
        $bool = $this->model->destroy($id);
        return $bool ? true : false;
    }

    // 获取自定义充值设置下拉列表
    public function getCustomRechargeSetSelectList($userInfo)
    {
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where = ['responsibility_person_id' => $responsibilityPersonIds];
        } else {
            $where = ['official_account_id' => $userInfo['cps_used_official_account_id']];
            // $where = [];
            if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
                $where['responsibility_person_id'] = $userInfo['cps_user_id'];
            }
        }

        $data = $this->model->getDataByWhere($where, 'id, name');
        return $data;
    }

    // 获取默认充值数据
    public function getDefaultChargeData($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;

        $where = [
            'is_common' => 1,
            'is_delete' => 0
        ];
        if (!empty($params['platform_type'])) $where['platform_type'] = $params['platform_type'];
        if (!empty($params['display_object'])) $where['display_object'] = $params['display_object'];

        $data = $this->moneyModel->getPagingDataByWhere($where, $page, $limit, 'platform_type, type, name, label, display_object, original_currency, recharge_price, send_currency, send_title');

        return $data;
    }

    // 批量设置充值模板
    public function batchSetRechargeTemplate($params)
    {
        $linkIds = explode(',', $params['link_ids']);

        $data = [];
        foreach ($linkIds as $id) {
            $data[] = [
                'id' => $id,
                'recharge_template_id' => $params['recharge_template_id'],
                'updated_at' => time()
            ];
        }

        $num = $this->linkModel->saveAll($data);

        if (!$num) {
            return ['message' => Error::SETTING_FAIL];
        }

        return [];
    }

    // 获取短剧的人均充值
    public function getPerCapitaByVideo(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        // 短剧id搜索
        if (!empty($params['video_id'])) {
            $where['video_id'] = $params['video_id'];
        }

        // 模板id搜索
        if (!empty($params['recharge_template_id'])) {
            $where['recharge_template_id'] = $params['recharge_template_id'];
        }

        $data = $this->statisticsVideoRechargeDataModel->getPagingDataByWhere($where, $page, $limit, 'sum(recharge_price) as recharge_price, video_id, video_name, recharge_template_type, sum(recharge_people_num) as recharge_people_num');

        foreach ($data['data'] as $key => $item) {
            // 计算人均
            $data['data'][$key]['per_capita'] = round($item['recharge_price'] / $item['recharge_people_num'], 2);
        }
        return $data;
    }
}